// pages/pk/pk.js
import {getNavSize, getSystemSize} from "../../utils/system"
import {ANSWERTYPE} from "../../core/enum"
import {Answer} from "../../model/answer"
import {Score} from "../../model/score"
Page({
	data: {
		items: [],
		current: 0,
		// answerIndex: Number,
		swiperHeight: Number,
		isChoose: false,
		rightCount: 0,
		wrongCount: 0,
		countStatus: false,
		totalTime: 0,
		doneMaskShow: false,
		isWrongAnswer: false,
		timer: 3,
		rightRate: 0,
		questionWords: [],
		waitAnswer: [],
		answer: [],
		countDownTime: 0,
		rightScore: 0,
		fastScore: 0,
		checkpoints: null,
		startMaskShow: false,
		showParse: false,
		parseHeight: Number
	},
	interval: null,
	_countDownTime: 0,
	accuTime: 0,
	_rightScore: 0,
	_fastScore: 0,
	checkpoints: null,
	onLoad: async function (options) {
		const res = await getSystemSize()
		const res1 = await getNavSize()
		const windowHeight = res.windowHeight
		const navigationHeight = res1.navigationHeight
		const statusBarHeight = res1.statusBarHeight
		const swiperHeight = windowHeight - navigationHeight - statusBarHeight

		this.checkpoints = await Answer.getRandomCps(options.cpid, options.count)
		if (this.checkpoints && this.checkpoints.linked_questions.length !== 0) {
			this.setData({
				items: this.checkpoints.linked_questions,
				swiperHeight: swiperHeight,
				parseHeight: swiperHeight,
				countStatus: false,
				checkpoints: this.checkpoints,
				startMaskShow: true
			})
			wx.setStorageSync("answer", this.checkpoints.id)
			this.calcReactQuestion()
		}
	},
	/**
	 * 计算倒计时时间
	 * */
	onCalcCountTime(option) {
		const countDownTime = option.detail.countDownTime
		this.accuTime = countDownTime
		this._countDownTime += 1
		if (countDownTime === 30) {
			this._countDownTime += 1
			this.calcWrongAnswer()
			this.setData({
				countStatus: false,
				// answerIndex: index
			})
		}
	},

	calcReactAnswer(item) {
		let answer = this.data.questionWords.concat(this.data.waitAnswer)
		answer = answer.join().replace(/,/g, '')
		if (answer === item.question.extra) {
			console.log(this.accuTime)
			if (this.accuTime >= 1 && this.accuTime <= 3) {
				this._fastScore += 2
			}
			if (this.accuTime >= 4 && this.accuTime <= 6) {
				this._fastScore += 1
			}
			this._rightScore += 2
			this.setData({
				rightScore: this._rightScore,
				fastScore: this._fastScore
			})
			this.calcRightAnswer()
		} else {
			this.calcWrongAnswer()
		}
	},

	onConfirm(event) {
		this.setData({
			countStatus: false
		})
		const item = event.currentTarget.dataset.item
		this.calcReactAnswer(item)
	},

	onSelectAnswer(event) {
		if (this.data.waitAnswer.indexOf('') === -1) {
			return
		}
		const item = event.currentTarget.dataset.item
		let answers = this.data.waitAnswer
		let index = answers.indexOf("")
		answers[index] = item.answer
		this.setData({
			waitAnswer: answers
		})
	},

	getRightAnswerIndex(current) {
		const topic = this.data.items[current]
		let index
		topic.question.answers.forEach((item, innerIndex) => {
			if (item.is_answer === true) {
				index = innerIndex
			}
		})
		return index
	},
	onChoose(event) {
		if (this.data.isChoose === true) {
			return
		}
		const chooseitem = event.currentTarget.dataset.chooseitem
		this.setData({
			countStatus: false,
			// answerIndex: event.currentTarget.dataset.index,
		})

		if (chooseitem.is_answer) {
			if (this.accuTime >= 1 && this.accuTime <= 3) {
				this._fastScore += 2
			}
			if (this.accuTime >= 4 && this.accuTime <= 6) {
				this._fastScore += 1
			}
			this._rightScore += 2
			this.setData({
				rightScore: this._rightScore,
				fastScore: this._fastScore
			})
			this.calcRightAnswer()
		} else {
			this.calcWrongAnswer()
		}
	},

	calcReactQuestion() {
		const reactItem = this.data.items.find(item => item.question.category === '交互题')
		console.log(reactItem)
		if (reactItem) {
			let questionWords = reactItem.question.question.split("")
			questionWords = questionWords.filter(i => i !== 'x' && i !== 'X')
			const length = reactItem.question.extra.length - questionWords.length
			let waitAnswer = []
			for (let i = 0; i < length; i++) {
				waitAnswer.push("")
			}
			this.setData({
				questionWords: questionWords,
				waitAnswer: waitAnswer
			})
		}
	},

	async calcRightRateAndTime() {
		let integerNum = parseInt(this._countDownTime / 60)
		let decimalNum = this._countDownTime % 60
		integerNum = integerNum.toString().length === 1 ? `0${integerNum}` : integerNum
		decimalNum = decimalNum.toString().length === 2 ? decimalNum : `0${decimalNum}`

		this.setData({
			countDownTime: `${integerNum}:${decimalNum}`
		})

		if (this.data.rightCount === 0) {
			this.setData({
				rightRate: 0
			})
		} else {
			let rate = (100 * (this.data.rightCount / this.data.items.length)).toFixed(1)
			this.setData({
				rightRate: `${rate}%`,
			})
		}
		if ((Number(this.data.rightScore) + Number(this.data.fastScore)) > Number(this.data.items.length * 2 * 2)) {
			wx.showToast({
				title: '系统错误, 请重新答题',
				icon: 'none'
			})
			setTimeout(() => {
				wx.navigateBack()
			}, 2000)
		}else {
			const score = await Score.uploadPoint({
				point: this.data.rightScore,
				duration: this.data.fastScore,
				checkpoint_id: this.checkpoints.id
			})
			if (score) {
				wx.removeStorageSync('answer')
				this.setData({
					doneMaskShow: true
				})
			}
		}
	},

	/**
	 * 处理错误答案
	 * */
	calcWrongAnswer() {
		let current = this.data.current
		let wrongCount = this.data.wrongCount
		this.setData({
			wrongCount: (wrongCount + 1),
			isWrongAnswer: true,
			isChoose: true,
			showParse: true,
			parseHeight: this.data.swiperHeight + 300
		})

		if (current + 1 === this.data.items.length) {
			clearInterval(this.interval)
			this.calcRightRateAndTime()
			return
		}
		// const transtionTimer = setInterval(() => {
		// 	this.refreshData(current + 1)
		// 	clearInterval(this.interval)
		// 	clearInterval(transtionTimer)
		// }, 3000)
		this.interval = setInterval(() => {
			let timer = this.data.timer
			this.setData({
				timer: timer - 1
			})
			if (this.data.timer === 0) {
				this.refreshData(current + 1)
				clearInterval(this.interval)
			}
		}, 1000)
	},

	/**￿
	 * 处理正确答案
	 * */
	calcRightAnswer() {
		let current = this.data.current
		let rightCount = this.data.rightCount
		this.setData({
			isChoose: true,
			rightCount: rightCount + 1
		})
		if (current + 1 === this.data.items.length) {
			clearInterval(this.interval)
			this.calcRightRateAndTime()
			return
		}
		// current: current + 1,
		// isChoose: false,
		// countStatus: true,
		this.setData({
			rightCount: rightCount + 1,
			showParse: true,
			parseHeight: this.data.swiperHeight + 300
		})
		this.interval = setInterval(() => {
			let timer = this.data.timer
			this.setData({
				timer: timer - 1
			})
			if (this.data.timer === 0) {
				this.refreshData(current + 1)
				clearInterval(this.interval)
			}
		}, 1000)
	},

	catchTouchMove(res) {
		return false;
	},

	onNext(event) {
		console.log(3123131)
		// const index = event.currentTarget.dataset.index
		clearInterval(this.interval)
		this.refreshData(this.data.current + 1)
	},

	refreshData(index) {
		this.setData({
			isWrongAnswer: false,
			current: index,
			isChoose: false,
			countStatus: true,
			showParse: false,
			parseHeight: this.data.swiperHeight,
			timer: 3
		})
	},

	onKnow() {
		wx.navigateBack()
	},
	onUnload() {
		this.setData({
			countStatus: false
		})
	},
	onCloseMask() {
		this.setData({
			startMaskShow: false,
			countStatus: true
		})
	}
})
